package com.example.demo.config;

import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.logging.Logger;

/**
 * 设置跨域，让前端允许访问后台的接口
 */
@Configuration
public class CORSConf {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            //配置虚拟路径和实体路径的映射关系
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/images/***")
                        .addResourceLocations("file:D:/file/");
            }
            //配置跨域的
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")      // 设置映射
                        .allowedOrigins("*")        // 设置域
                        .allowedMethods("*")               // 设置请求的方式GET、POST等
                        .allowedHeaders("*");              // 设置头
            }
            //添加了拦截请求的代码
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new MyInterceptor())//配置拦截器
                        .addPathPatterns("/**/**")//要拦截的请求路径，**表示我们拦截所有的请求路径
                        .excludePathPatterns("/noLogin/**")//除了带有noLogin路径的请求路径不拦截
                        .excludePathPatterns("/detail");//除了带有detail路径的请求路径不拦截
            }
        };
    }
}